<?php

namespace Modules\Admin\Http\Controllers\Categories;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Common\General\Security\Api\Gateway;
use Modules\Common\Models\AdminLog;
use Modules\Common\Models\Categories;
use Modules\Common\Models\Ebooks;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;
use GuzzleHttp\Client;


class Import
{
    /**
     *
     * @Route(path=/api/admin/category-import-ebook method=post)
     */
    public function crawl()
    {
        $sxToken = request('sx-token');
        $page = request('page', 1);
        $pageSize = request('pageSize', 10);
        $url = request('url');
        $categoryId = request('category_id');
    
        // 验证参数
        if (!$url) {
            return response()->json(['error' => 'URL参数是必需的！'], 400);
        }
    
        // 设置请求头
        $headers = [
            'Referer' => 'http://bzrmtzx.w.chineseall.cn/',
            'Sx-Token' => $sxToken,
        ];
    
        // 创建 Guzzle 客户端
        $client = new Client();
        try {
            // 发送请求
            $response = $client->request('GET', $url, [
                'headers' => $headers,
                'query' => [
                    'page' => $page,
                    'pageSize' => $pageSize,
                ],
            ]);
            
            // 检查响应状态
            if ($response->getStatusCode() == 200) {
                $dataArray = json_decode($response->getBody(), true);
                if ($dataArray && $dataArray['success']) {
                    $books = $this->extractBooks($dataArray['list'], $categoryId);
                    $this->storeBooks($books);
                    return Api::success();
                } else {
                    return Api::fail(500, '爬取数据失败，未获取到成功标志');
                }
            } else {
                return Api::fail(500, '爬取数据失败，响应状态码非200');
            }
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
    
    protected function extractBooks($list, $categoryId)
    {
        $books = [];
        foreach ($list as $group) {
            if (isset($group['list'])) {
                foreach ($group['list'] as $book) {
                    $books[] = $this->createBookArray($book, $categoryId);
                }
            } else {
                $books[] = $this->createBookArray($group, $categoryId);
            }
        }
        return $books;
    }
    
    protected function createBookArray($book, $categoryId)
    {
        $eidDefault = auth('api')->user()->eid; 
        $sidDefault = auth('api')->user()->sid; 
        return [
            'assetsId' => $book['id'] ?? '0',
            'book_name' => $book['name'] ?? '暂无书名',
            'description' => $book['intro'] ?? '暂无描述',
            'cover_image' => $book['coverImgUrl'] ?? '暂无封面',
            'author' => $book['author'] ?? '暂无作者',
            'publisher' => $book['publisher'] ?? '暂无出版社',
            'publish_date' => $book['publishDate'] ?? '暂无出版日期',
            'price' => $book['price'] ?? '0.00',
            'underlined_price' => $book['price'] ?? '0.00',
            'format' => "epub",
            'isbn' => $book['isbn'] ?? '无',
            'url' => "http://gxlib.w.chineseall.cn/book/detail/{$book['shId']}", // 确保URL参数是正确编码的
            'category_id' => $categoryId,
            'is_free' => 1, // 是否免费：1是 2否
            'available' => 1,
            'is_upload' => 2, // 是否上传 1：是 2：爬取
            'is_recommend' => 2,
            'admin_user_id' => 1,
            'is_published' => 1,
            'eid' => $eidDefault,
            'sid' => $sidDefault,
            'created_at' => now()->format('Y-m-d H:i:s'), // 格式化日期时间
        ];
    }
    
    protected function storeBooks($books)
    {
        $uniqueBooks = [];
        foreach ($books as $book) {
            if (! Ebooks::where('assetsId', $book['assetsId'])->exists()) {
                $uniqueBooks[] = $book;
            }
        }
        if (count($uniqueBooks) > 0) {
            Ebooks::insert($uniqueBooks);
        }
    }

}